<?php

namespace App\Service\Common;

use Carbon\Carbon;
use Illuminate\Validation\ValidationException;
use Ramsey\Uuid\Uuid;

class UploadService
{
    /**
     * 上传文件到ftp
     * @param array $request
     * @return array
     * @throws ValidationException
     */
    public function uploadToFtp(array $request): array
    {
        $file = !empty($request['file']) ? $request['file'] : null;
        $prefix = !empty($request['prefix']) ? $request['prefix'] : '';
        if (!empty($prefix)) $prefix = '/'.$prefix;

        if (!$file) {
            throw ValidationException::withMessages(['message' => '请上传文件']);
        }

        // 保存文件
        $extension = $file->extension();
        $filName = Uuid::uuid4()->getHex().'.'.$extension;
        $path = $file->storeAs('uploads/'. $prefix . Carbon::now()->format('Ymd'), $filName, 'ftp');

        return [
            'name' => $filName,
            'domain' => config('filesystems.disks.ftp.domain'),
            'path' => $path,
            'url' => config('filesystems.disks.ftp.domain').'/'.$path,
            'driver' => 'ftp'
        ];
    }
}
